import React, { useState, useEffect } from 'react'
import './index.modules.scss'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx'
import {
  Form,
  Input,
  Button,
  Select,
  message,
  Table,
  Space,
  Popconfirm,
  Pagination,
  Modal,
  Divider
} from 'antd'
import { getstorelistAll, storeInventoryAdd2 } from '@/http/api/store'
import { filmListSelect, filmListSelectExcel } from '@/http/api/carBrand'
import { number2List, number3List } from '@/http/api/number'
import { provinceQualitNumber } from '@/components/js/addressOptions'
let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]
let serchFilm = {
  appid: localStorage.getItem('appid')
}
const App = () => {
  useEffect(() => {
    getStore()
    getCounterNumber()
    getqutailsCode()
  }, [])
  const [form] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage()
  const [optionsStore, setOptionsStore] = useState([])
  const [filmNameList, serFilmNameList] = useState([])
  const [customerServiceNumber, SetcustomerServiceNumber] = useState('')
  const [number2ListData, setnumber2List] = useState([])
  const [number3ListData, setnumber3List] = useState([])
  const [tabelListData, settabelListData] = useState([])
  const [detilsData, setDetilsData] = useState([])
  const [isShowDetils, setisShowDetils] = useState(false)
  let filmName = ''
  const columns = [
    {
      title: '产品名称',
      dataIndex: 'filmType',
      align: 'center'
    },
    {
      title: '切分日期',
      dataIndex: 'filmId2',
      align: 'center'
    },
    {
      title: '切分机长代码',
      dataIndex: 'filmId3',
      align: 'center'
    },
    {
      title: '品检代码',
      dataIndex: 'filmId4',
      align: 'center'
    },
    {
      title: '大卷代码',
      dataIndex: 'filmId5',
      align: 'center'
    },
    {
      title: '小卷序号',
      dataIndex: 'filmId6',
      align: 'center'
    },

    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            onClick={() => {
              getFilmData(data)
              // setDetilsData(data)
            }}
          >
            详情
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  let pageData = {
    page: 1,
    size: 10,
    total: 0
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
  }
  const DeleteFn = (data) => {
    settabelListData(
      tabelListData.filter((item) => {
        if (item.key != data.key) return item
      })
    )
  }
  const getFilmData = async (data) => {
    let res = await filmListSelectExcel({
      nameNumber: data.filmType,
      appid: localStorage.getItem('appid')
    })
    if (res.data.res) {
      setDetilsData(res.data.res)
      setisShowDetils(true)
    } else {
      messageApi.error('未查询到对应产品')
    }
  }
  const upXlsFn = () => {
    const fileInput = document.getElementById('excelFile')
    fileInput.click()
    fileInput.addEventListener('change', async (e) => {
      const file = e.target.files[0]
      const reader = new FileReader()
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })

        // 获取第一个工作表
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
        // 转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(firstSheet)
        console.log(jsonData)
        settabelListData(
          jsonData.map((item, index) => {
            let data = {
              key: index,
              code: item.code.toUpperCase(),
              filmType: item.code.substring(0, 2).toUpperCase(),
              filmId2: item.code.substring(2, 8).toUpperCase(),
              filmId3: item.code.substring(8, 10).toUpperCase(),
              filmId4: item.code.substring(10, 12).toUpperCase(),
              filmId5: item.code.substring(13, 14).toUpperCase(),
              filmId6: item.code.substring(15, 18).toUpperCase()
            }
            return data
          })
        )
      }
      reader.readAsArrayBuffer(file)
    })
  }
  // 添加按钮
  const onFinish = async (data) => {
    if (form.getFieldValue().storeId) {
      let upData = {
        storeId: form.getFieldValue().storeId,
        region: form.getFieldValue().region,
        customerService: form.getFieldValue().customerService,
        table: tabelListData,
        appid: localStorage.getItem('appid'),
        customerServicePhone: JSON.parse(localStorage.getItem('userInfo')).phone
      }
      const res = await storeInventoryAdd2(upData)
      messageApi.success(res.data.message)
    } else {
      messageApi.error('请选择门店')
    }
    // console.log(data)
  }
  // 获取所有门店列表
  const getStore = async () => {
    const res = await getstorelistAll({
      appid: localStorage.getItem('appid'),
      status: 1
    })

    setOptionsStore([
      ...res.data.res.map((item) => {
        return {
          value: item._id,
          label: item.name,
          region: item.region.includes('[')
            ? JSON.parse(item.region)[0]
            : item.region
        }
      })
    ])
  }
  // 获取品检
  // 获取所有门店列表
  const getqutailsCode = async () => {
    const res = await number2List({ size: 100000, page: 1 })
    const res2 = await number3List({ size: 100000, page: 1 })

    setnumber2List([
      ...res.data.res.map((item) => {
        return {
          value: item.code,
          label: item.code
        }
      })
    ])
    setnumber3List([
      ...res2.data.res.map((item) => {
        return {
          value: item.code,
          label: item.code
        }
      })
    ])
  }
  // 获取客服id
  const getCounterNumber = () => {
    form.setFieldsValue({
      customerService: JSON.parse(localStorage.getItem('userInfo'))
        .customerService
    })
    SetcustomerServiceNumber(
      JSON.parse(localStorage.getItem('userInfo')).customerService
    )
  }
  // 修改选择后重新获取膜列表
  const getFilmList = async () => {
    const res = await filmListSelect(serchFilm)
    serFilmNameList(
      res.data.res.map((item) => {
        return {
          value: item._id,
          label: item.name,
          ...item
        }
      })
    )
    if (form.getFieldValue().number3 && form.getFieldValue().number2) {
      // let regex = /\b[a-zA-Z]+\b/g
      // let filmTypeNumber = form.getFieldValue().filmType
      // let regionNumber = form.getFieldValue().region
      let number3 = form.getFieldValue().number3
      let number2 = form.getFieldValue().number2
      let QualityNumber = dayjs().format('YYMMDD')
      let code = JSON.parse(localStorage.getItem('userInfo')).code

      form.setFieldsValue({
        startNumber: `${filmName}${QualityNumber}${code}${number2}-${number3}-01`,
        endNumber: `${filmName}${QualityNumber}${code}${number2}-${number3}-`
      })
    }
  }
  // 选择膜
  const selectFilmName = (data) => {
    console.log(filmNameList)
    filmNameList.forEach((item) => {
      if (item.value == data) {
        form.setFieldsValue({
          filmAge: item.age,
          count: item.countAll,
          lacquerNumber: item.lacquerNumber,
          roofNumber: item.roofNumber,
          sunNumber: item.sunNumber,
          colorAlterationNumber: item.colorAlterationNumber
        })
        filmName = item.name
      }
    })
  }
  return (
    <div className=" addQualityNumberCenterBox ">
      <div className="centerCar">
        <div className="center">
          <div className="Card" style={{ minHeight: '41px' }}>
            <Form
              name="basic"
              labelCol={{
                span: 6
              }}
              wrapperCol={{
                span: 16
              }}
              style={{
                maxWidth: 600
              }}
              initialValues={{
                remember: true
              }}
              form={form}
              onFinish={onFinish}
              autoComplete="off"
            >
              <Form.Item
                label="收货门店"
                name="storeId"
                rules={[
                  {
                    required: true,
                    message: '请输入'
                  }
                ]}
              >
                <Select
                  showSearch
                  allowClear
                  style={{
                    width: '100%'
                  }}
                  placeholder="请选择"
                  filterOption={(input, option) =>
                    (option?.label ?? '')
                      .toLowerCase()
                      .includes(input.toLowerCase())
                  }
                  options={optionsStore}
                  onChange={(data, data2) => {
                    serchFilm.storeId = data
                    form.setFieldsValue({
                      region: data2.region
                    })
                    getFilmList()
                  }}
                />
              </Form.Item>
            </Form>
            <div className="center">
              <Button onClick={upXlsFn}>点击上传表格</Button>
              <input
                className="upFelis"
                type="file"
                id="excelFile"
                accept=".xlsx, .xls"
              />
            </div>
            <div className="center" style={{ margin: '20px 0' }}>
              <Button onClick={onFinish}>确定发货</Button>
              <input
                className="upFelis"
                type="file"
                id="excelFile"
                accept=".xlsx, .xls"
              />
            </div>
          </div>
        </div>
        <div className="center">
          <div className="Card" style={{ minHeight: '41px' }}>
            <Form
              name="basic"
              labelCol={{
                span: 6
              }}
              wrapperCol={{
                span: 16
              }}
              style={{
                maxWidth: 600
              }}
              initialValues={{
                remember: true
              }}
              form={form}
              onFinish={onFinish}
              autoComplete="off"
            >
              <Form.Item
                label="客服编号 "
                name="customerService"
                rules={[
                  {
                    required: true,
                    message: '请输入'
                  }
                ]}
              >
                <Input
                  disabled
                  className="inputeStyle"
                  placeholder="请输入客服编号"
                />
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
      <div className="tableBox">
        <Table
          rowSelection={{
            type: 'checkbox'
          }}
          pagination={false}
          bordered
          rowKey="key"
          columns={columns}
          dataSource={tabelListData}
        />
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </div>
      <Modal
        title="详情"
        open={isShowDetils}
        footer={[]}
        onCancel={() => {
          setisShowDetils(false)
        }}
      >
        <div className="detilsBox">
          <div className="card" style={{ width: '369px', padding: '15px' }}>
            <div className="cardtitle">产品信息</div>
            <Divider style={{ margin: '10px 0' }} />
            <div className="headerCarContent">
              <div className="Content align_center">
                <div className="ContentTitle">产品类型：</div>
                <div className="ContentSize">{detilsData.type}</div>
              </div>

              <div className="Content align_center">
                <div className="ContentTitle">产品型号：</div>
                <div className="ContentSize">{detilsData.name}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">产品编号：</div>
                <div className="ContentSize">{detilsData.nameNumber}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">质保年限：</div>
                <div className="ContentSize">{detilsData.age}</div>
              </div>

              <div className="Content align_center">
                <div className="ContentTitle">总使用次数：</div>
                <div className="ContentSize">{detilsData.countAll}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">漆面膜使用次数：</div>
                <div className="ContentSize">{detilsData.lacquerNumber}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">改色膜使用次数：</div>
                <div className="ContentSize">
                  {detilsData.colorAlterationNumber}
                </div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">车顶膜使用次数：</div>
                <div className="ContentSize">{detilsData.roofNumber}</div>
              </div>
              <div className="Content align_center">
                <div className="ContentTitle">太阳膜使用次数：</div>
                <div className="ContentSize">{detilsData.sunNumber}</div>
              </div>
            </div>
          </div>
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
}
export default App
